<?php

/**
 * 这是对象实现迭代的另一个示例
 * 为文件指针属性实现迭代
 * 其实PHP有个名为SplFileObject的类已经直接实现了这个功能。
 * User: ford
 * Date: 15-6-18
 * Time: 下午1:14
 */
class FileIterator implements Iterator {
	private $filePoint;
	private $index = 0;
	private $line;

	function __construct($fileName) {
		$fp = fopen($fileName, 'r');
		if(!$fp) {
			die('Cannot open ' . $fileName .' for reading.<br />');
		} else {
			$this->filePoint = $fp;
		}

		$this->line = rtrim(fgets($this->filePoint), "\n");
	}

	function rewind() {
		$this->index = 0;
		rewind($this->filePoint);	//这是PHP的文件操纵函数，它指向文件开头
		$this->line = rtrim(fgets($this->filePoint), "\n");
	}

	function current() {
		return $this->line;
	}

	function key() {
		return $this->index;
	}

	function next() {
		$this->index++;
		$this->line = rtrim(fgets($this->filePoint), "\n");
		if(!feof($this->filePoint)) {
			return $this->line;
		} else {
			return null;
		}
	}

	/**
	 * 检查是否继续循环的条件
	 * @return bool
	 */
	function valid() {
		return feof($this->filePoint) ? false : true;
	}

}

$x = new FileIterator('qbf.txt');


//下面循环中的第二个参数代表key,读取它的时候自然会执行$x的key方法，自然读取$value的也候也就执行current方法
foreach($x as $lineNo => $value) {
	echo "$lineNo: \t $value <br />\n";
}

//下面用内置的PHP类直接生成同样的功能
$x = new SplFileObject('qbf.txt', 'r');

foreach($x as $lineNo => $value) {
	if(!empty($value)) {
		echo $lineNo .':' . $value .'<br />';
	}
}